﻿using System;
using System.Collections.Generic;
using Assist;
using Autodesk.Revit.DB;
using Autodesk.Revit.DB.Architecture;
using SectionSignAndFilled.StairsRoomSection.DataDefine;
using SectionSignAndFilled.StairsRoomSection.ElementPacket;

namespace SectionSignAndFilled.StairsRoomSection.Kit.CutLine
{
	internal class StairsRunCutLineGetter : CutLineGetter
	{
		public override bool GetCutLines(SectionViewData ViewInfoRay, ElementObject elemObj)
		{
			List<Curve> collection = new List<Curve>();
			SectionViewData sectionViewData;
			base.TransformViewData(elemObj, ViewInfoRay, out sectionViewData);
			Line secLine = sectionViewData.m_SecLine;
			if (!CommonFun.SureElementInPlanLine(elemObj.SelfElem.UseElement, secLine, sectionViewData.m_viewDir))
			{
				return true;
			}
			Document linkDocument = CommonFun.getLinkDocument(elemObj.SelfElem);
			if (!this.GetElemCutLineInDocument(ViewInfoRay, sectionViewData, elemObj, linkDocument, ref collection))
			{
				return true;
			}
			elemObj.m_lstCutLine.AddRange(collection);
			return true;
		}

		private bool GetElemCutLineInDocument(SectionViewData ViewInfoRay, SectionViewData ViewInfo, ElementObject elemObj, Document doc, ref List<Curve> lstCutLines)
		{
			try
			{
				StairsRun stairsRun = doc.GetElement(elemObj.SelfElem.UseElement.Id) as StairsRun;
				Element element = doc.GetElement(stairsRun.GetTypeId());
				Parameter parameter = element.get_Parameter(BuiltInParameter.STAIRS_TRISERTYPE_RISER_TREAD_CONNECTION);
				parameter.AsInteger();
				if (parameter == null)
				{
					return false;
				}
				if (!parameter.IsReadOnly)
				{
					parameter.Set(2);
				}
				doc.Regenerate();
				elemObj.GetLinkTran();
				XYZ normal = ViewInfo.m_viewDir.Normalize();
				Plane plane = RevitVersionFuncs.CreatePlanByNormalAndOrigin(normal, ViewInfo.m_SecLine.Evaluate(0.5, true));
				lstCutLines = CommonFun.CutElement(elemObj.SelfElem.UseElement, ViewInfo, plane);
			}
			catch (Exception)
			{
				return true;
			}
			lstCutLines = CommonFun.TranCurve(lstCutLines, elemObj.GetLinkTran());
			this.FindStructLayer(ref lstCutLines, ViewInfoRay);
			return true;
		}

		private void FindStructLayer(ref List<Curve> curves, SectionViewData viewSectionInfo)
		{
			List<List<Curve>> list = CutLineGetter.DivStairsCurves(curves, viewSectionInfo);
			curves = new List<Curve>();
			if (list == null || list.Count == 0)
			{
				return;
			}
			int num = 0;
			int index = 0;
			for (int i = 0; i < list.Count; i++)
			{
				if (i == 0)
				{
					num = list[i].Count;
					index = i;
				}
				else if (num > list[i].Count)
				{
					num = list[i].Count;
					index = i;
				}
			}
			curves.AddRange(list[index]);
		}
	}
}
